package com.hejian.android.a72ggametools.imageloader;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 磁盘缓存
 * Created by Administrator on 2016/1/11.
 */
public class DiskCache implements ImageCache {
    static String cacheDir = "/sdcard/cache/";

    /**
     * 本地获取文件
     * @param urlStr
     * @return
     */
    @Override
    public Bitmap getBitmap(String urlStr) {
        String fileName = getNameFromUrl(urlStr);
        Bitmap result = BitmapFactory.decodeFile(cacheDir+fileName);
        return result;
    }

    /**
     * 写入本地
     * @param urlStr
     * @param bitmap
     */
    @Override
    public void setImage(String urlStr, Bitmap bitmap) {
        FileOutputStream fileOutputStream = null;
        String fileName = getNameFromUrl(urlStr);
        try {
            fileOutputStream = new FileOutputStream(cacheDir+fileName);
            bitmap.compress(Bitmap.CompressFormat.PNG,100,fileOutputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private String getNameFromUrl(String urlStr) {
        return urlStr.substring(urlStr.lastIndexOf("/")+1,urlStr.length());
    }
}
